package logger

import (
	"fmt"
	"sync"
	"time"
)

// ComponentTracker 组件跟踪器
type ComponentTracker struct {
	logger *EnhancedPerformanceLogger
	mu     sync.RWMutex
}

// NewComponentTracker 创建组件跟踪器
func NewComponentTracker(logger *EnhancedPerformanceLogger) *ComponentTracker {
	return &ComponentTracker{
		logger: logger,
	}
}

// TrackRBC 跟踪RBC组件延迟
func (ct *ComponentTracker) TrackRBC(operation string, instanceID, round, epoch int) *RBCLatencyTracker {
	return &RBCLatencyTracker{
		component:  "RBC",
		operation:  operation,
		instanceID: instanceID,
		round:      round,
		epoch:      epoch,
		startTime:  time.Now(),
		tracker:    ct,
	}
}

// TrackABA 跟踪ABA组件延迟
func (ct *ComponentTracker) TrackABA(operation string, instanceID, round, epoch int) *ABALatencyTracker {
	return &ABALatencyTracker{
		component:  "ABA",
		operation:  operation,
		instanceID: instanceID,
		round:      round,
		epoch:      epoch,
		startTime:  time.Now(),
		tracker:    ct,
	}
}

// TrackCommonCoin 跟踪CommonCoin组件延迟
func (ct *ComponentTracker) TrackCommonCoin(operation string, instanceID, round, epoch int) *CommonCoinLatencyTracker {
	return &CommonCoinLatencyTracker{
		component:  "CommonCoin",
		operation:  operation,
		instanceID: instanceID,
		round:      round,
		epoch:      epoch,
		startTime:  time.Now(),
		tracker:    ct,
	}
}

// TrackCBR 跟踪CBR组件延迟
func (ct *ComponentTracker) TrackCBR(operation string, instanceID, round, epoch int) *CBRLatencyTracker {
	return &CBRLatencyTracker{
		component:  "CBR",
		operation:  operation,
		instanceID: instanceID,
		round:      round,
		epoch:      epoch,
		startTime:  time.Now(),
		tracker:    ct,
	}
}

// TrackProofChain 跟踪ProofChain组件延迟
func (ct *ComponentTracker) TrackProofChain(operation string, instanceID, round, epoch int) *ProofChainLatencyTracker {
	return &ProofChainLatencyTracker{
		component:  "ProofChain",
		operation:  operation,
		instanceID: instanceID,
		round:      round,
		epoch:      epoch,
		startTime:  time.Now(),
		tracker:    ct,
	}
}

// BaseLatencyTracker 基础延迟跟踪器
type BaseLatencyTracker struct {
	component  string
	operation  string
	instanceID int
	round      int
	epoch      int
	startTime  time.Time
	tracker    *ComponentTracker
}

// Finish 完成延迟跟踪
func (blt *BaseLatencyTracker) Finish(success bool, errorMsg string) {
	endTime := time.Now()
	blt.tracker.logger.RecordComponentLatency(
		blt.component,
		blt.operation,
		blt.startTime,
		endTime,
		blt.instanceID,
		blt.round,
		blt.epoch,
		success,
		errorMsg,
	)
}

// RBCLatencyTracker RBC延迟跟踪器
type RBCLatencyTracker struct {
	BaseLatencyTracker
}

// TrackSend 跟踪RBC发送操作
func (rlt *RBCLatencyTracker) TrackSend() *RBCLatencyTracker {
	rlt.operation = "RBC_SEND"
	return rlt
}

// TrackEcho 跟踪RBC Echo操作
func (rlt *RBCLatencyTracker) TrackEcho() *RBCLatencyTracker {
	rlt.operation = "RBC_ECHO"
	return rlt
}

// TrackReady 跟踪RBC Ready操作
func (rlt *RBCLatencyTracker) TrackReady() *RBCLatencyTracker {
	rlt.operation = "RBC_READY"
	return rlt
}

// TrackDeliver 跟踪RBC Deliver操作
func (rlt *RBCLatencyTracker) TrackDeliver() *RBCLatencyTracker {
	rlt.operation = "RBC_DELIVER"
	return rlt
}

// ABALatencyTracker ABA延迟跟踪器
type ABALatencyTracker struct {
	BaseLatencyTracker
}

// TrackBVAL 跟踪ABA BVAL操作
func (alt *ABALatencyTracker) TrackBVAL() *ABALatencyTracker {
	alt.operation = "ABA_BVAL"
	return alt
}

// TrackAUX 跟踪ABA AUX操作
func (alt *ABALatencyTracker) TrackAUX() *ABALatencyTracker {
	alt.operation = "ABA_AUX"
	return alt
}

// TrackCONF 跟踪ABA CONF操作
func (alt *ABALatencyTracker) TrackCONF() *ABALatencyTracker {
	alt.operation = "ABA_CONF"
	return alt
}

// TrackFINAL 跟踪ABA FINAL操作
func (alt *ABALatencyTracker) TrackFINAL() *ABALatencyTracker {
	alt.operation = "ABA_FINAL"
	return alt
}

// CommonCoinLatencyTracker CommonCoin延迟跟踪器
type CommonCoinLatencyTracker struct {
	BaseLatencyTracker
}

// TrackGenCoin 跟踪CommonCoin生成操作
func (cclt *CommonCoinLatencyTracker) TrackGenCoin() *CommonCoinLatencyTracker {
	cclt.operation = "COMMON_COIN_GEN"
	return cclt
}

// TrackCombineShares 跟踪CommonCoin组合份额操作
func (cclt *CommonCoinLatencyTracker) TrackCombineShares() *CommonCoinLatencyTracker {
	cclt.operation = "COMMON_COIN_COMBINE"
	return cclt
}

// CBRLatencyTracker CBR延迟跟踪器
type CBRLatencyTracker struct {
	BaseLatencyTracker
}

// TrackCBRDistribute 跟踪CBR分发操作
func (cbrlt *CBRLatencyTracker) TrackCBRDistribute() *CBRLatencyTracker {
	cbrlt.operation = "CBR_DISTRIBUTE"
	return cbrlt
}

// TrackCBRReply 跟踪CBR回复操作
func (cbrlt *CBRLatencyTracker) TrackCBRReply() *CBRLatencyTracker {
	cbrlt.operation = "CBR_REPLY"
	return cbrlt
}

// TrackCBRReady 跟踪CBR Ready操作
func (cbrlt *CBRLatencyTracker) TrackCBRReady() *CBRLatencyTracker {
	cbrlt.operation = "CBR_READY"
	return cbrlt
}

// ProofChainLatencyTracker ProofChain延迟跟踪器
type ProofChainLatencyTracker struct {
	BaseLatencyTracker
}

// TrackProofGen 跟踪ProofChain生成操作
func (pclt *ProofChainLatencyTracker) TrackProofGen() *ProofChainLatencyTracker {
	pclt.operation = "PROOF_CHAIN_GEN"
	return pclt
}

// TrackProofVerify 跟踪ProofChain验证操作
func (pclt *ProofChainLatencyTracker) TrackProofVerify() *ProofChainLatencyTracker {
	pclt.operation = "PROOF_CHAIN_VERIFY"
	return pclt
}

// TrackProofChain 跟踪ProofChain链接操作
func (pclt *ProofChainLatencyTracker) TrackProofChain() *ProofChainLatencyTracker {
	pclt.operation = "PROOF_CHAIN_LINK"
	return pclt
}

// ComponentLatencyAnalyzer 组件延迟分析器
type ComponentLatencyAnalyzer struct {
	logger *EnhancedPerformanceLogger
}

// NewComponentLatencyAnalyzer 创建组件延迟分析器
func NewComponentLatencyAnalyzer(logger *EnhancedPerformanceLogger) *ComponentLatencyAnalyzer {
	return &ComponentLatencyAnalyzer{
		logger: logger,
	}
}

// AnalyzeComponentPerformance 分析组件性能
func (cla *ComponentLatencyAnalyzer) AnalyzeComponentPerformance() map[string]ComponentPerformanceAnalysis {
	latencies := cla.logger.GetComponentLatencies()
	analysis := make(map[string]ComponentPerformanceAnalysis)

	components := []string{"RBC", "ABA", "CommonCoin", "CBR", "ProofChain"}
	
	for _, component := range components {
		componentLatencies := latencies[component]
		if len(componentLatencies) == 0 {
			analysis[component] = ComponentPerformanceAnalysis{
				Component: component,
				Status:    "No data",
			}
			continue
		}

		// 计算性能指标
		var totalLatency, maxLatency, minLatency int64
		var successOps, failedOps int
		
		totalLatency = 0
		maxLatency = 0
		minLatency = int64(^uint64(0) >> 1)
		
		for _, latency := range componentLatencies {
			totalLatency += latency.Duration
			if latency.Duration > maxLatency {
				maxLatency = latency.Duration
			}
			if latency.Duration < minLatency {
				minLatency = latency.Duration
			}
			
			if latency.Success {
				successOps++
			} else {
				failedOps++
			}
		}

		avgLatency := totalLatency / int64(len(componentLatencies))
		successRate := float64(successOps) / float64(len(componentLatencies)) * 100

		// 性能评估
		var status string
		if successRate >= 95.0 && avgLatency < 100 {
			status = "Excellent"
		} else if successRate >= 90.0 && avgLatency < 200 {
			status = "Good"
		} else if successRate >= 80.0 && avgLatency < 500 {
			status = "Fair"
		} else {
			status = "Poor"
		}

		analysis[component] = ComponentPerformanceAnalysis{
			Component:   component,
			AvgLatency: avgLatency,
			MaxLatency: maxLatency,
			MinLatency: minLatency,
			TotalOps:   len(componentLatencies),
			SuccessOps: successOps,
			FailedOps:  failedOps,
			SuccessRate: successRate,
			Status:     status,
		}
	}

	return analysis
}

// ComponentPerformanceAnalysis 组件性能分析
type ComponentPerformanceAnalysis struct {
	Component   string  `json:"component"`
	AvgLatency  int64   `json:"avg_latency_ms"`
	MaxLatency  int64   `json:"max_latency_ms"`
	MinLatency  int64   `json:"min_latency_ms"`
	TotalOps    int     `json:"total_operations"`
	SuccessOps  int     `json:"success_operations"`
	FailedOps   int     `json:"failed_operations"`
	SuccessRate float64 `json:"success_rate"`
	Status      string  `json:"status"`
}

// GeneratePerformanceReport 生成性能报告
func (cla *ComponentLatencyAnalyzer) GeneratePerformanceReport() string {
	analysis := cla.AnalyzeComponentPerformance()
	
	report := "=== EbbFlow组件性能分析报告 ===\n\n"
	
	for _, component := range []string{"RBC", "ABA", "CommonCoin", "CBR", "ProofChain"} {
		comp := analysis[component]
		report += fmt.Sprintf("【%s】\n", component)
		report += fmt.Sprintf("  状态: %s\n", comp.Status)
		report += fmt.Sprintf("  平均延迟: %dms\n", comp.AvgLatency)
		report += fmt.Sprintf("  最大延迟: %dms\n", comp.MaxLatency)
		report += fmt.Sprintf("  最小延迟: %dms\n", comp.MinLatency)
		report += fmt.Sprintf("  总操作数: %d\n", comp.TotalOps)
		report += fmt.Sprintf("  成功率: %.2f%%\n", comp.SuccessRate)
		report += "\n"
	}
	
	return report
}
